<?php

namespace app\common;

use app\models\User;
use yii\web\Controller;

class BaseController extends Controller
{
    public $enableCsrfValidation = false;
    public $userInfo = null;
    public function beforeAction($action)
    {
//        $this->enableCsrfValidation = false;
        /*跨域*/
        header("Access-Control-Allow-Credentials:true");
        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
        $allow_origin = array(
            'http://localhost:8080',
            'http://192.168.0.104:8080'
        );
        if (in_array($origin,$allow_origin)) {
            header("Access-Control-Allow-Origin:".$origin);
            header('Access-Control-Allow-Headers: X-Requested-With');
        }
        $token = \Yii::$app->request->post('token', '');
        if (empty($token)){
            $token = \Yii::$app->request->get('token', '');
        }
        if ($action->id !== 'login'){
            try{
                if ($token){
                    $userInfo = User::find()->where(['token' => $token]);
                    if ($userInfo){
                        $this->userInfo = $userInfo;
                    }else{
                        throw new \Exception('noAuth');
                    }
                }else{
                    throw new \Exception('noAuth');
                }
            }catch (\Exception $e){
                echo $this->result([], 403, '用户未登录');
                return false;
            }
        }

        return parent::beforeAction($action);
    }

    public function result($data, $code = 0, $msg = ''){
        return json_encode([
            'code' => $code,
            'data' => $data,
            'msg' => $msg
        ]);
    }
}
